package com.iretailer.report.quartz.sendReqularly.protocol;

import com.iretailer.report.model.SendRegularly;
import com.iretailer.report.quartz.sendReqularly.model.FlowArray;
import com.iretailer.report.quartz.sendReqularly.model.ServerConfig;
import com.iretailer.report.quartz.sendReqularly.util.CommonUtil;
import com.iretailer.report.util.StringUtil;
import com.iretailer.report.util.TimeUtil;
import com.jcraft.jsch.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Properties;

/**
 * @Auther: xjw
 * @Date: 2019/8/1 0001 10:27
 * @Description:
 */
public class SFTPProtocol {

    // SFTP 服务器地址IP地址
    private String host;

    // SFTP 端口
    private int port;

    // SFTP 登录用户名
    private String username;

    // SFTP 登录密码
    private String password;

    // 私钥
    private String privateKey;

    public SFTPProtocol(String host, int port, String username, String password, String privateKey) {
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
        this.privateKey = privateKey;
    }

    public static boolean initAndSend(SendRegularly s, ServerConfig config, String fileName, byte[] message) throws Exception {
        SFTPProtocol sftp = new SFTPProtocol(config.getHost(), config.getPort(), config.getUserName(), config.getPassword(), config.getPrivateKey());
        return sftp.upload(config.getDirectory(), fileName, message);
    }

    /**
     * 将输入流的数据上传到sftp作为文件。
     *
     * @param filePath 上传到该目录
     * @param fileName sftp端文件名
     * @param message  输入流
     */
    public boolean upload(String filePath, String fileName, byte[] message) throws Exception {
        boolean result = false;
        // 登录
        JSch jsch = new JSch();
        if (privateKey != null) {
            // 设置私钥
            jsch.addIdentity(privateKey);
        }
        Session session = jsch.getSession(username, host, port);
        if (password != null) {
            session.setPassword(password);
        }
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");

        session.setConfig(config);
        session.connect();

        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftp = (ChannelSftp) channel;

        InputStream is = null;
        //上传文件
        try {
//            byte[] header = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
//            byte[] csv_data = message.getBytes(Charset.forName(LOCAL_CHARSET));
//            ByteArrayOutputStream os = new ByteArrayOutputStream();
//            os.write(header);
//            os.write(csv_data);
            is = new ByteArrayInputStream(message);
//            os.close();
//            is = new ByteArrayInputStream(CommonUtil.Json2CSV(message, FlowArray.class).getBytes(Charset.forName(LOCAL_CHARSET)));
            sftp.cd(filePath);
            sftp.put(is, fileName);
            result = true;
        } catch (SftpException e) {
            throw new RuntimeException(String.format("sftp server not have this path %s", filePath));
        } finally {
            if (is != null) {
                is.close();
            }
            //关闭
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
            if (session.isConnected()) {
                session.disconnect();
            }
        }
        return result;
    }


}
